<template>
  <div id="popupbody" v-if="dialogVisible">
    <div class="popupbody-box">
      <div class="popupbody-title">
        <span>搜索/校验/更新局域网设备</span>
        <span class="el-icon-close" @click="closePOpup"></span>
      </div>
      <div class="popupbody-boxin" style="padding:10px;">
        <!--      end-->
        <el-table :data="arryList"
                  height="400"
                  tooltip-effect="dark"
                  ref="table">
          <el-table-column label="设备号" align="center">
            <template slot-scope="scope">
              {{ scope.row.mac }}
            </template>
          </el-table-column>
          <el-table-column label="IP地址" align="center">
            <template slot-scope="scope">
              {{ scope.row.ip }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="popupbody-footer">
        <el-button size="small" @click="closePOpup">返回</el-button>
<!--        <el-button size="small" @click="refrendFn()">更新设备状态</el-button>-->
        <el-button type="primary" size="small" @click="submitFormAdd()">确认并添加/更新设备</el-button>
      </div>
    </div>
  </div>
</template>

<script>

const os = require('os'); //操作系统
const request = require('request');

export default {
  name: 'studentMultiple',
  props: ['visible', 'dynamicTagsArray'],
  data() {
    return {
      dialogVisible: this.visible,
      arryList: [],
      deviceOption: [],
      getDeviceList:[],
      // 距离转换
      minrssi: {
        "-127": 0,
        "-51": 0.5,
        "-60": 1,
        "-63": 2,
        "-66": 3,
        "-68": 4,
        "-70": 5,
        "-72": 6,
        "-74": 7,
        "-76": 8,
        "-78": 9,
        "-80": 10,
        "-82": 11,
        "-84": 12,
        "-86": 13,
        "-88": 14,
        "-90": 15
      }
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        this.loadGateways()
      }else{
        this.arryList = []
        this.deviceOption = []
      }
    }
  },
  created() {
  },
  methods: {
    // 提交数据
    async submitFormAdd() {
      let dataJson = await this.$post(this.api.corner.renew, {list: JSON.stringify(this.arryList)})
      if(!dataJson.code){
        // window.localStorage.setItem('deviceIp', JSON.stringify(this.deviceOption))
        window.localStorage.removeItem('getDeviceList')
        window.localStorage.setItem('getDeviceList', JSON.stringify(this.getDeviceList))
        this.$emit('updateDevice')
        this.closePOpup()
      }else{
        this.$message.error(dataJson.msg)
      }
      // this.$emit('studentFn', this.applyBox)
    },
    // refrendFn(){
    //   console.log('arryList:', this.arryList)
    //   // window.localStorage.setItem('deviceIp', JSON.stringify(this.deviceOption))
    //   // getDeviceList
    //   this.$emit('updateDevice')
    //   this.closePOpup()
    // },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    // 获取可接收的盒子的信息
    loadGateways(node) {
      let n = this
      let interfaces = os.networkInterfaces();
      let ips = [];
      for (var intf in interfaces) {
        if (interfaces[intf][0].mac.internal === true)
          continue;

        ips = ips.concat(interfaces[intf].filter(function (e) {
          if ((e.family === "IPv4") && (e.internal == false) && !e.address.startsWith("169.254")) {
            return true;
          }
          return false;
        }))
      }

      let s_mask;
      let ip;
      let s_addr;
      let start_addr;
      let end_addr;
      let addr;
      ips.forEach(function (e) {
        var _start = 0;
        var _end = -1;
        var mask = 0;
        s_mask = e.netmask + ".";
        for (var i = 0; i < 4; i++) {
          _start = _end + 1;
          _end = s_mask.indexOf(".", _start);
          mask = (mask << 8) + parseInt(s_mask.substring(_start, _end));
        }
        _start = 0;
        _end = -1;
        ip = 0;
        s_addr = e.address + ".";

        for (var i = 0; i < 4; i++) {
          _start = _end + 1;
          _end = s_addr.indexOf(".", _start);
          ip = (ip << 8) + parseInt(s_addr.substring(_start, _end));
        }
        var base = mask & ip;
        ip = base;
        start_addr = (0xFF & (ip >> 24)).toString() + "." + (0xFF & (ip >> 16)) + "." + (0xFF & (ip >> 8)) + "." + (ip & 255);

        for (; (mask & ip) == base; ip++) {
          end_addr = (0xFF & (ip >> 24)).toString() +
              "." +
              (0xFF & (ip >> 16)) +
              "." +
              (0xFF & (ip >> 8)) +
              "." +
              (ip & 255);
          addr = "http://" + end_addr + "/info";
          request({uri: addr, timeout: 20000}, function (err, resp, body) {
            if (err)
              return;

            var data;
            try {
              data = JSON.parse(body);
            } catch (e) {
              //console.log(e);
            }

            if (data && data.mac && data.hardwareVer && data.hardwareVer && data.hardwareVer.startsWith("4.")) {
              var suffix = data.mac.replace(/:/g, "");
              console.log('addr:', addr)
              console.log('获取的数据内容信息：', suffix, resp, resp.request.host)
              n.getInfomation(resp.request.host)
            }
          })
        }
      });
    },
    // 获取id内盒子信息
    async getInfomation(ip) {
      let n = this;
      console.log('查验设备==========》》》》', this.deviceOption[ip])
      if (this.deviceOption.indexOf(ip) === -1) {
        this.deviceOption.push(ip)
        let {data} = await this.axios.get('http://' + ip + '/info', {})
        console.log('=======================dataJson：', data)
        let newLine = {}
        newLine.mac = data.mac;
        newLine.ip = ip;
        newLine.scope = -127;
        newLine.data = data
        n.arryList.push(n.getJson(newLine))
        n.getDeviceList.push(data.mac) // 在线的识别器ip 进行在线验证
        // console.log('this.deviceOption:', n.arryList)
      }
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
.popupbody-boxin {
  min-width: 700px;
}
</style>
